package actors

import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl.Behaviors
import akka.stream.Materializer
import org.joda.time.DateTime
import play.api.libs.ws.WSClient
import tool.Pojo._
import tool.Tool
import utils.Utils

import scala.concurrent.duration._
import scala.language.postfixOps
import scala.concurrent.ExecutionContext.Implicits.global


/**
 * Created by yz on 13/4/2020
 */
object MissionManager {

  case object TimerKey

  def apply()(implicit dao: MyDao, ws: WSClient, materializer: Materializer): Behavior[MissionManager] = Behaviors.setup { context =>
    implicit val missionDao = dao.missionDao
    implicit val modeDao = dao.modeDao
    missionDao.selectAll("running").map { missions =>
      missions.foreach { mission =>
        val missionWrap = MissionWrap(mission)
        context.self ! missionWrap
      }
    }
    Behaviors.withTimers { timers =>
      timers.startTimerAtFixedRate(TimerKey, Ask, 3 seconds)
      Behaviors.receiveMessage[MissionManager] { message =>
        message match {
          case Ask =>
            val totalMissions = Utils.execFuture(missionDao.selectAll("wait"))
            val canRunMissions = totalMissions.sortBy(_.startTime.getMillis)
            if (!canRunMissions.isEmpty) {
              val mission = canRunMissions(0)
              val missionExecutor = context.spawn(MissionExecutor(mission), s"${mission.id}")
              missionExecutor ! RunAction
            }
            Behaviors.same
          case MissionWrap(mission) =>
            val newMission = mission.copy(state = "wait")
            missionDao.update(newMission)
            Behaviors.same
        }

      }

    }

  }

}
